import { Inject, Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm'
import { UserEntity } from '../entity/user';
import axios from 'axios';
import privacy from '../privacy';
import { JwtService } from '@midwayjs/jwt';
import { RedisService } from '@midwayjs/redis';
import { ClassfootEntity } from '../entity/classtify';
import { ShopclassEntity } from '../entity/shopclass';
import { ShopEntity } from '../entity/shop';
import { SearchDTO } from '../dto/Search';




/**
 * 描述
 */
@Provide()
export class MdService {


    @Inject()
    jwtService: JwtService;
    @Inject()
    RedisService: RedisService;

    //  操作数据库
    @InjectEntityModel(UserEntity)
    UserModel: Repository<UserEntity>;


    @InjectEntityModel(ClassfootEntity)
    ClassfootModel: Repository<ClassfootEntity>;

    @InjectEntityModel(ShopclassEntity)
    ShopclassModel: Repository<ShopclassEntity>;

    @InjectEntityModel(ShopEntity)
    ShopModel: Repository<ShopEntity>;

    /**
     * 描述
     */
    async login(code: string) {

        console.log("服务", code);
        //  得到code码发送给微信服务器

        let { data } = await axios({
            url: "https://api.weixin.qq.com/sns/jscode2session",
            params: {
                appid: privacy.appid,
                secret: privacy.appSecret,
                js_code: code,
                grant_type: "authorization_code"

            }
        })

        console.log(data);
        if (!data.openid) {
            return {
                code: 40004,
                message: "参数多无"
            }
        }

        // openid  查询数据库 
        let userinfo = await this.UserModel.findOne({ where: { openid: data.openid } })

        console.log("用户信息", userinfo);
        if (!userinfo) {
            console.log("执行了");
            //  没有用户信息
            let user = new UserEntity()
            user.openid = data.openid
            user.session_key = data.session_key

            userinfo = await this.UserModel.save(user)
        }

        let token = this.jwtService.signSync({ userinfo }, privacy.tokenSECRET, {
            expiresIn: "2d"
        })

        // let result3: any = {}
        // try {
        //     result3 = this.jwtService.verifySync(token + "321321352", privacy.tokenSECRET, { complete: true })
        //     console.log("11111111", result3);

        //     console.log("666666666666666666", result3.payload.userinfo);
        // }catch{

        // }


        return { code: 20000, message: data.openid, userinfo, token }
    }


    async getfoods() {

        //  查询分类的数据库
        //    createQueryBuilder("a")  赋予当前的表 为 a 表 
        let result = await this.ClassfootModel.createQueryBuilder("a")
            .leftJoinAndSelect("a.foods", "foods")
            .getMany()

        return {
            code: 20000,
            data: result
        }

    }

    async getshopfood(id: any) {
        //  查询店铺的信息
        //  店铺的实体数据库               取表名 as
        let result = await this.ShopModel
            .createQueryBuilder("shop")
            .leftJoinAndSelect("shop.shopfoodsclassify", "classfoods")
            .leftJoinAndSelect("classfoods.foods", "foods")
            .leftJoinAndSelect("foods.spu", "spu")
            .leftJoinAndSelect("spu.sku", "sku")
            .where({ id: id })
            .getOne()

        return {
            code: 20000,
            data: {
                shop: result
            }
        }
    }

    async getshop(option: SearchDTO) {
        //  查询分类的数据库
        //    createQueryBuilder("a")  赋予当前的表 为 a 表 
        //   (page -1)*  size
        let { page, size } = option
        var num = (page - 1) * size
        let result = await this.ShopModel.createQueryBuilder()
            // 114.059155,22.721894
            .select(`st_distance_sphere(POINT(${option.longitude},${option.latitude}), POINT(longitude, latitude))`, 'distance')
            .addSelect(['id', "name", "sell", "start", "express", "img"
                , "longitude", "latitude"
            ])
            // .having('distance < 10000')
            .orderBy('distance')
            .skip(num)
            .take(size)
            .getRawMany();

        return {
            code: 20000,
            data: result
        }

    }
    async getclassify() {

        //  查询分类的数据库
        //    createQueryBuilder("a")  赋予当前的表 为 a 表 
        let result = await this.ShopclassModel.find()

        return {
            code: 20000,
            data: result
        }

    }







    /**
     * 发送订阅消息
     */
    async tosubsrc(openid: string) {

        // var message = {
        //     "name1": {
        //         "value": "卓标"
        //     },
        //     "time3": {
        //         "value": "2023/6/2"
        //     },
        //     thing4: {
        //         "value": "明德云饺"
        //     },
        //     thing6: {
        //         value: "可以开始用餐:取餐号位:520"
        //     },
        //     thing7: {
        //         value: "韭菜饺子"
        //     }

        // }

        let access_token = await this.RedisService.get("access_token")

        console.log("token", access_token);
        let { data } = await axios({
            url: "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token,
            method: "post",
            data: {
                template_id: "1KCVEvdX0YJCsC-deQH9q6VBS1CrU_67TXkpsY3uFmQ",
                page: "pages/index/index?id=666",
                //  this.options.id
                touser: 'o01r05GFEhChHXtOsnRcWtnapChc',
                data: {
                    "name1": {
                        "value": "卓标"
                    },
                    "time3": {
                        "value": "2023/6/2"
                    },
                    "thing4": {
                        "value": "明德云饺"
                    },
                    "thing6": {
                        "value": "可以开始用餐:取餐号位:520"
                    },
                    "thing7": {
                        "value": "韭菜饺子"
                    }
                },
                miniprogram_state: "developer",
                lang: "zh_CN"

            }
        })


        console.log("订阅信息", data);

        return {
            message: "66666"
        }
    }


    /**
     * 更新头像
     */
    async updatauserinfo() {
        //  怎么知道他是谁呢? 判断对方有没有 带个token
        //  有token 就拿着token 来解析数据 
    }
    /**
     * 手机号码
     */
    async updatausertell() {
        //  怎么知道他是谁呢? 判断对方有没有 带个token
        //  有token 就拿着token 来解析数据 
    }
    /**
     * 下单
     */
    async commitOrder() {
        //  怎么知道他是谁呢? 判断对方有没有 带个token
        //  有token 就拿着token 来解析数据 
    }

}
